import { useEffect, useState } from 'react';
import ResizeObserver from 'resize-observer-polyfill';
import { BasicTarget, getTargetElement, getElementFixPosition } from '../utils/dom';

type Size = { width: number; height: number; left: number; top: number };

function usePosition(target: BasicTarget): Size | undefined {
  const [position, setPosition] = useState<Size>();

  useEffect(() => {
    const element = getTargetElement(target);
    const observer = new ResizeObserver((entries) => {
      entries.forEach((entry) => {
        const [left, top, width, height] = getElementFixPosition(entry.target);
        setPosition({ left, top, width, height });
      });
    });

    observer.observe(element);
    return () => {
      observer.disconnect();
    };
  }, []);

  return position;
}

export default usePosition;
